const express = require('express');
const router = express.Router();
const User = require('../models/User');
const Message = require('../models/Message');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');

// 获取好友列表
router.get('/', auth, async (req, res) => {
  try {
    const user = await User.findById(req.userId)
      .populate('friends.userId', 'username avatar bio');
    
    const friends = user.friends
      .filter(f => f.status === 'accepted')
      .map(f => ({
        _id: f.userId._id,
        username: f.userId.username,
        avatar: f.userId.avatar,
        bio: f.userId.bio,
        addedAt: f.addedAt
      }));
    
    res.json(friends);
  } catch (error) {
    console.error('获取好友列表失败:', error);
    res.status(500).json({ message: '获取好友列表失败' });
  }
});

// 发送好友请求
router.post('/request/:userId', auth, async (req, res) => {
  try {
    const targetUserId = req.params.userId;
    
    // 检查是否是自己
    if (targetUserId === req.userId) {
      return res.status(400).json({ message: '不能添加自己为好友' });
    }
    
    // 检查目标用户是否存在
    const targetUser = await User.findById(targetUserId);
    if (!targetUser) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 检查是否已经是好友
    const currentUser = await User.findById(req.userId);
    const alreadyFriend = currentUser.friends.some(
      f => f.userId.toString() === targetUserId && f.status === 'accepted'
    );
    
    if (alreadyFriend) {
      return res.status(400).json({ message: '该用户已经是您的好友' });
    }
    
    // 检查是否已经发送过请求
    const existingRequest = targetUser.friendRequests.find(
      r => r.from.toString() === req.userId && r.status === 'pending'
    );
    
    if (existingRequest) {
      return res.status(400).json({ message: '已经向该用户发送过好友请求' });
    }
    
    // 添加好友请求
    targetUser.friendRequests.push({
      from: req.userId,
      status: 'pending',
      sentAt: new Date()
    });
    
    await targetUser.save();
    
    res.status(201).json({ message: '好友请求已发送' });
  } catch (error) {
    console.error('发送好友请求失败:', error);
    res.status(500).json({ message: '发送好友请求失败' });
  }
});

// 处理好友请求
router.patch('/request/:requestId', auth, async (req, res) => {
  try {
    const { action } = req.body;
    if (!['accept', 'reject'].includes(action)) {
      return res.status(400).json({ message: '无效的操作' });
    }
    
    const user = await User.findById(req.userId);
    const requestIndex = user.friendRequests.findIndex(
      r => r._id.toString() === req.params.requestId
    );
    
    if (requestIndex === -1) {
      return res.status(404).json({ message: '好友请求不存在' });
    }
    
    const request = user.friendRequests[requestIndex];
    
    if (action === 'accept') {
      // 接受请求，双方添加好友
      user.friends.push({
        userId: request.from,
        status: 'accepted',
        addedAt: new Date()
      });
      
      // 更新请求状态
      request.status = 'accepted';
      
      // 给对方也添加好友关系
      const otherUser = await User.findById(request.from);
      otherUser.friends.push({
        userId: req.userId,
        status: 'accepted',
        addedAt: new Date()
      });
      
      await Promise.all([user.save(), otherUser.save()]);
      
      res.json({ message: '已接受好友请求' });
    } else {
      // 拒绝请求
      request.status = 'rejected';
      await user.save();
      
      res.json({ message: '已拒绝好友请求' });
    }
  } catch (error) {
    console.error('处理好友请求失败:', error);
    res.status(500).json({ message: '处理好友请求失败' });
  }
});

// 获取好友请求列表
router.get('/requests', auth, async (req, res) => {
  try {
    const user = await User.findById(req.userId)
      .populate('friendRequests.from', 'username avatar');
    
    const requests = user.friendRequests
      .filter(r => r.status === 'pending')
      .map(r => ({
        _id: r._id,
        from: {
          _id: r.from._id,
          username: r.from.username,
          avatar: r.from.avatar
        },
        sentAt: r.sentAt
      }));
    
    res.json(requests);
  } catch (error) {
    console.error('获取好友请求失败:', error);
    res.status(500).json({ message: '获取好友请求失败' });
  }
});

module.exports = router; 